package cn.edu.jlu.community.app.sign;

import android.annotation.TargetApi;
import android.os.Build;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import com.avos.avoscloud.AVException;
import com.avos.avoscloud.SignUpCallback;

import butterknife.ButterKnife;
import butterknife.OnClick;
import cn.edu.jlu.community.R;
import cn.edu.jlu.community.app.MainActivity;
import cn.edu.jlu.community.server.AppServer;
import cn.edu.jlu.community.util.ToastUtil;


public class SignUpFragment extends SignFragment {

    private String mToken;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.sign_up_fragment, container, false);
        ButterKnife.inject(this, view);
        return view;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    @Override public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
    }


    @OnClick(R.id.switch_sign_mode_text)
    protected void onSwitchModeTextClick() {
        ((SignActivity) getActivity()).setMode(SignActivity.Mode.MODE_SIGN_IN);
    }


    /**
     * Attempts to sign in or register the account specified by the login form.
     * If there are form errors (invalid email, missing fields, etc.), the
     * errors are presented and no actual login attempt is made.
     */
    @Override
    public void doSignAction() {

        // Reset errors.
        mUsernameView.setError(null);
        mPasswordView.setError(null);

        // Store values at the time of the sign up attempt.
        String username = mUsernameView.getText().toString();
        String password = mPasswordView.getText().toString();

        boolean valid = false;
        View focusView = null;


        // Check for a valid phone number.
        if (!checkPhone()) {
            focusView = mUsernameView;
        }
        // Check for a valid password.
        else if (!checkPassword()) {
            focusView = mPasswordView;
        }
        // All field valid.
        else { valid = true; }


        if (valid) {
            AppServer.signUp(username,password,new SignUpCallback() {
                @Override
                public void done(AVException e) {
                    if(null==e){
                        ToastUtil.showText("注册成功");
                        startActivity(MainActivity.class);
                        getActivity().finish();
                    }else {
                        ToastUtil.showText("注册失败");
                    }
                }
            });
        } else {
            // There was an error; don't attempt sign up and focus the first
            // form field with an error.
            focusView.requestFocus();
        }
    }

    private boolean checkPhone() {
        String phone = mUsernameView.getText().toString();
        boolean result = false;

        if (TextUtils.isEmpty(phone)) {
            mUsernameView.setError(getString(R.string.error_field_required));
        } else if (!isPhoneValid(phone)) {
            mUsernameView.setError(getString(R.string.error_invalid_phone));
        } else {
            result = true;
        }

        return result;
    }

    private boolean checkPassword() {
        String password = mPasswordView.getText().toString();
        boolean result = false;

        if (TextUtils.isEmpty(password)) {
            mPasswordView.setError(getString(R.string.error_field_required));
        } else if (!isPasswordValid(password)) {
            mPasswordView.setError(getString(R.string.error_invalid_password));
        } else {
            result = true;
        }

        return result;
    }

    private boolean isPhoneValid(String phone) {
        //TODO: Add phone number verify logic
        return true;
    }

    private boolean isPasswordValid(String password) {
        //TODO: Add password verify logic
        return password.length() >= 4;
    }

    /**
     * Shows the progress UI and hides the login form.
     */
    @TargetApi(Build.VERSION_CODES.HONEYCOMB_MR2)
    public void showProgress(final boolean show) {
//        // On Honeycomb MR2 we have the ViewPropertyAnimator APIs, which allow
//        // for very easy animations. If available, use these APIs to fade-in
//        // the progress spinner.
//        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB_MR2) {
//            int shortAnimTime = getResources().getInteger(android.R.integer.config_shortAnimTime);
//
//            mLoginFormView.setVisibility(show ? View.GONE : View.VISIBLE);
//            mLoginFormView.animate().setDuration(shortAnimTime).alpha(
//                    show ? 0 : 1).setListener(new AnimatorListenerAdapter() {
//                @Override
//                public void onAnimationEnd(Animator animation) {
//                    mLoginFormView.setVisibility(show ? View.GONE : View.VISIBLE);
//                }
//            });
//
//            mProgressView.setVisibility(show ? View.VISIBLE : View.GONE);
//            mProgressView.animate().setDuration(shortAnimTime).alpha(
//                    show ? 1 : 0).setListener(new AnimatorListenerAdapter() {
//                @Override
//                public void onAnimationEnd(Animator animation) {
//                    mProgressView.setVisibility(show ? View.VISIBLE : View.GONE);
//                }
//            });
//        } else {
//            // The ViewPropertyAnimator APIs are not available, so simply show
//            // and hide the relevant UI components.
//            mProgressView.setVisibility(show ? View.VISIBLE : View.GONE);
//            mLoginFormView.setVisibility(show ? View.GONE : View.VISIBLE);
//        }
    }
}
